﻿Public Class HDDocDiForm

    Private _AlarmTypeParse As New Hashtable()
    Private _AlarmTypeCode As New Hashtable()
    Private _NetIDList As New SortedList()

    Private Sub HDDocDiForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.DataGridView1.AutoGenerateColumns = False


        dtpTo.Value = UtilityClass.GetDateString(Now)
        dtpFrom.Value = dtpTo.Value.AddDays(-1).ToLongDateString()

        LoadRef()
    End Sub

    Private Sub LoadRef()
        Dim rts As RefTypeService = New RefTypeService(MainForm.pi)

        cboRef.Items.Add("所有库房") 'Add <ALL>
        For Each rti As RefTypeItem In rts.GeRefGroupList()
            cboRef.Items.Add(rti)
            If Not _NetIDList.ContainsKey(rti.NetId) Then _NetIDList.Add(rti.NetId, Nothing)
        Next

        cboRef.SelectedIndex = -1
        btnRefresh.Enabled = False
        btnPrint.Enabled = False
    End Sub

    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub btnRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRefresh.Click
        bwSearch.CancelAsync()
        If sender.Text = "取消" Then
            sender.Text = "正在取消..."
            sender.Enabled = False
            Exit Sub
        End If

        If CheckValidate() = False Then
            Exit Sub
        End If


        If rowChangeList.Count > 0 Then
            Select Case ShowSaveConfim()
                Case Windows.Forms.DialogResult.Yes
                    btnSave_Click(btnSave, e)
                    BeforeRefreshControlState()
                    RefreshData()
                    'AfterRefreshControlState()
                Case Windows.Forms.DialogResult.No
                    btnSave.Enabled = False
                    rowChangeList.Clear()
                    BeforeRefreshControlState()
                    RefreshData()
                    'AfterRefreshControlState()
                Case Windows.Forms.DialogResult.Cancel

            End Select
        Else
            BeforeRefreshControlState()
            RefreshData()
            'AfterRefreshControlState()
        End If


    End Sub
    Private Sub BeforeRefreshControlState()
        'Me.Cursor = Cursors.WaitCursor
        'Me.DataGridView1.Cursor = Cursors.WaitCursor
        'Me.DataGridView1.Enabled = False
        Me.lblSearchState.Text = String.Empty
        Me.pbSearch.Value = 0
        Me.pnlSearch.Visible = True
        'Me.btnRefresh.Enabled = False
        Me.btnRefresh.Text = "取消"
        Me.dtpFrom.Enabled = False
        Me.dtpTo.Enabled = False
        Me.btnPrint.Enabled = False
        Me.cboRef.Enabled = False
        Me.isLoading = True
    End Sub
    Private Sub AfterRefreshControlState()
        Me.isLoading = False
        Me.cboRef.Enabled = True
        Me.dtpFrom.Enabled = True
        Me.dtpTo.Enabled = True

        Me.btnRefresh.Enabled = True
        Me.btnRefresh.Text = "查询"
        'Me.pnlSearch.Visible = False
        'Me.DataGridView1.Enabled = True
        'Me.DataGridView1.Cursor = Cursors.Default
    End Sub

    ''' <summary>
    ''' 刷新数据
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub RefreshData()
        If cboRef.SelectedIndex = -1 Then Return
        'Dim strSql As String
        'Dim m_str As String
        'Dim m_alarmexis As Boolean = False
        'Dim m_lastalarm As Boolean = False

        _AlarmTypeParse.Clear()
        _AlarmTypeCode.Clear()
        Me.DataGridView1.Rows.Clear()
        Me.DataGridView1.Columns.Clear()

        AddDataGridViewColumns()
        SetDataGridViewColumnVisible(False)

        '初始化残缺数据列表
        Dim keys(_NetIDList.Keys.Count - 1) As Integer
        _NetIDList.Keys.CopyTo(keys, 0)
        For Each netID As Integer In keys
            _NetIDList.Item(netID) = Nothing
        Next

        '检索报警数据及残缺数据
        Dim bwParam As New ArrayList()
        If cboRef.SelectedItem.GetType IsNot GetType(RefTypeItem) Then '<ALL>
            Me.lblSearchState.Text = String.Format("正在查询{0}历史报警数据……", Me.cboRef.SelectedItem)
            For i As Integer = 0 To cboRef.Items.Count - 1
                If i <> cboRef.SelectedIndex Then
                    Dim rti As RefTypeItem = cboRef.Items(i)
                    Dim dList = Nothing
                    If _NetIDList(rti.NetId) Is Nothing Then '同一设备只检查一次
                        dList = New List(Of AlarmEvent)()
                        _NetIDList(rti.NetId) = dList
                    End If
                    bwParam.Add(New Object() {rti, dList})
                    'RefreshDataHelper(rti, dList)
                    'bwSearch.RunWorkerAsync(New Object() {rti, dList})
                End If
            Next
        Else 'Not <ALL>
            Dim rti As RefTypeItem = cboRef.SelectedItem
            Me.lblSearchState.Text = String.Format("正在查询{0}历史报警数据……", rti.RefName)
            Dim dList = Nothing
            If _NetIDList(rti.NetId) Is Nothing Then '同一设备只检查一次
                dList = New List(Of AlarmEvent)()
                _NetIDList(rti.NetId) = dList
            End If
            bwParam.Add(New Object() {rti, dList})
            'RefreshDataHelper(cboRef.SelectedItem, dList)
            'bwSearch.RunWorkerAsync(New Object() {cboRef.SelectedItem, dList})
        End If
        bwSearch.RunWorkerAsync(bwParam)

    End Sub
    Private Sub RefreshDataGridViewNo()
        isSorting = True
        For i As Integer = 0 To DataGridView1.Rows.Count - 1
            DataGridView1.Rows(i).Cells(0).Value = i + 1
        Next
        isSorting = False
    End Sub
   

    Private Function RefreshDataHelper(ByVal cbo_rti As RefTypeItem, ByVal dList As List(Of AlarmEvent)) As Hashtable
        Dim strSql As String
        Dim tempStr As String


        Dim col As String = ""
        Dim col1 As String = ""
        Dim m_ailist As IList(Of Integer) = New List(Of Integer)
        Dim m_aiNamelist As New List(Of String)
        Dim alarmstatus_DoorValid As Boolean = False
        Dim alarmstatus_Door2Valid As Boolean = False
        Dim alarmstatus_LosPowerValid As Boolean = False
        Dim cRow, pRow As DataRow : pRow = Nothing
        Dim earlyTime, lastlyTime As DateTime
        earlyTime = DateTime.MaxValue
        

       

        strSql = String.Format("select a.netID, a.pageIndex, a.RowIndex, a.pageStartTime, a.startTime ")


        Dim eventList As New Hashtable()

       
        Dim tablename_DoorAlarm As String = ""

        Dim diopts As DiDoPortTypeService = New DiDoPortTypeService(cbo_rti)
        Dim tablename_Door2Alarm As String = ""
        
        tablename_DoorAlarm = String.Format("Ref{0}_DoorState", cbo_rti.RefId.ToString())


        tablename_Door2Alarm = String.Format("Ref{0}_DoorState", (cbo_rti.RefId + 4).ToString)

        '获取DIO端口
        For Each diopti As DiDoPortTypeItem In diopts.GetDioGroupList()
            strSql &= String.Format(",a." & tablename_DoorAlarm) '由于需要检测相同行
            If diopti.DoorStatusPort >= 1 Then
                eventList.Add(tablename_DoorAlarm, New List(Of AlarmEvent)) '添加警报事件列表
                If _AlarmTypeParse(tablename_DoorAlarm) = Nothing Then _AlarmTypeParse(tablename_DoorAlarm) = 121 + cbo_rti.RefId * 10
                If _AlarmTypeCode(121 + cbo_rti.RefId * 10) = Nothing Then _AlarmTypeCode(121 + cbo_rti.RefId * 10) = tablename_DoorAlarm
                alarmstatus_DoorValid = True
            End If

            strSql &= String.Format(",a." & tablename_Door2Alarm) '由于需要检测相同行
            If diopti.DoorStatusPort2 >= 1 Then
                eventList.Add(tablename_Door2Alarm, New List(Of AlarmEvent)) '添加警报事件列表
                If _AlarmTypeParse(tablename_Door2Alarm) = Nothing Then _AlarmTypeParse(tablename_Door2Alarm) = 122 + cbo_rti.RefId * 10
                If _AlarmTypeCode(122 + cbo_rti.RefId * 10) = Nothing Then _AlarmTypeCode(122 + cbo_rti.RefId * 10) = tablename_Door2Alarm
                alarmstatus_Door2Valid = True
            End If

          
        Next






        tempStr = strSql
        strSql &= String.Format(" From tbcchddidata_{0} AS a  Where a.startTime >= '{1}' and a.startTime<='{2}' and a.netID='{3}' and id=0 order by a.startTime, a.pageIndex, a.RowIndex", _
                                cbo_rti.ProjectID.Replace("-", "_"), UtilityClass.GetDateString(Me.dtpFrom.Value), UtilityClass.GetDateString(Me.dtpTo.Value), cbo_rti.NetId)

        Dim tmpObj As Object
        Dim ds As DataSet
        'ds = SqlHelper.ExecuteDataset(strSql, Nothing)

        Select Case MainForm.readConfig("SystemType")
            Case 2
                ds = SqlHelper1.ExecuteDataset(strSql, Nothing)
            Case Else
                ds = SqlHelper.ExecuteDataset(strSql, Nothing)
        End Select

        If ds.Tables.Count = 0 Then Return Nothing

        'Dim tempTime As New Hashtable()
        '获取历史警报数据
        For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
            If bwSearch.CancellationPending Then Return Nothing '取消查询
            Dim r As DataRow = ds.Tables(0).Rows(i)
            cRow = r
            ''检测数据完整性
            'If dList IsNot Nothing AndAlso i > 0 Then
            '    If Not CheckIntegrity(cRow, pRow, dList) Then
            '        pRow = cRow
            '        Continue For
            '    End If
            'End If
            '检测最早时间点
            tmpObj = r("startTime")
            If UtilityClass.IsNotNullEmpty(tmpObj) = False Then Continue For
            lastlyTime = tmpObj
            If lastlyTime < earlyTime Then
                earlyTime = lastlyTime
            End If
            '检测当前行是否与前一行相同（断电）
            If i > 0 Then
                Dim isSame As Boolean = True
                Dim cRowArr(), pRowArr() As Object
                cRowArr = cRow.ItemArray : pRowArr = pRow.ItemArray
                For j As Integer = 0 To cRowArr.Length - 1
                    If j < 1 OrElse j > 3 Then
                        If Not IsDBNull(cRowArr(j)) AndAlso Not IsDBNull(pRowArr(j)) Then 'both not null
                            If cRowArr(j) <> pRowArr(j) Then
                                isSame = False
                                Exit For
                            End If
                        ElseIf IsDBNull(cRowArr(j)) <> IsDBNull(pRowArr(j)) Then 'one is null
                            isSame = False
                            Exit For
                        End If
                    End If
                Next j
                If isSame Then
                    pRow = cRow
                    Continue For '若检测为相同行，则跳过改行
                End If
            End If

            If alarmstatus_DoorValid = True Then
                If Not IsDBNull(r(tablename_DoorAlarm)) Then '库门开关状态
                    Dim alarmType As Integer = _AlarmTypeParse(tablename_DoorAlarm)
                    Dim list As List(Of AlarmEvent)
                    list = eventList(tablename_DoorAlarm)

                    If r(tablename_DoorAlarm) = g_On Then '报警
                        If list.Count <= 0 Then 'first
                            Dim headRow As DataRow = r
                            Dim hRow As DataRow = FindAlarmRealHeader(tablename_DoorAlarm, r("startTime"), cbo_rti.ProjectID.Replace("-", "_"), r("netID"), r("pageIndex"), r("RowIndex"), tempStr, g_On)
                            If hRow IsNot Nothing Then headRow = hRow

                            '检测最早时间点
                            If headRow("startTime") < earlyTime Then
                                earlyTime = headRow("startTime")
                            End If

                          
                            AddEventToList("库门1", alarmType, headRow, list, cbo_rti)
                        Else
                            If list(list.Count - 1).EndTime <> Nothing Then
                                AddEventToList("库门1", alarmType, r, list, cbo_rti)
                            Else 'first g_off; 2008-10-31; 处理同一条记录包含多个报警开始点，为其中一个报警添加备注后，其余报警无法显示问题
                                If cRow("pageIndex") = pRow("pageIndex") AndAlso cRow("RowIndex") = pRow("RowIndex") AndAlso cRow("startTime") = pRow("startTime") Then
                                    If r("alarmType") = alarmType Then
                                        If list.Count > 0 Then
                                            
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    Else '正常
                        If list.Count > 0 Then
                            If list(list.Count - 1).EndTime = Nothing Then '报警未结束
                                list(list.Count - 1).EndTime = r("startTime") '设置报警结束
                            End If
                        Else
                            If i = 0 Then
                                Dim hRow As DataRow = FindAlarmRealHeader(tablename_DoorAlarm, r("startTime"), _
                                                                                cbo_rti.ProjectID.Replace("-", "_"), _
                                                                                r("netID"), _
                                                                                r("pageIndex"), _
                                                                                r("RowIndex"), _
                                                                                tempStr, _
                                                                                g_Off _
                                                            )
                                If hRow IsNot Nothing Then
                                    AddEventToList("库门1", alarmType, hRow, list, cbo_rti)
                                    'list(list.Count - 1).EndTime = r("startTime")
                                    Dim fRow As DataRow = FindAlarmRealFooter(tablename_DoorAlarm, hRow("startTime"), Me.dtpTo.Value, _
                                                                                    cbo_rti.ProjectID.Replace("-", "_"), _
                                                                                    r("netID"), _
                                                                                    hRow("pageIndex"), _
                                                                                    hRow("RowIndex"), _
                                                                                    tempStr _
                                                            )
                                    If fRow IsNot Nothing Then
                                        If fRow("startTime") >= Me.dtpFrom.Value Then '报警结束时间>=起始时间
                                            '检测最早时间点
                                            If list(list.Count - 1).StartTime < earlyTime Then
                                                earlyTime = list(list.Count - 1).StartTime
                                            End If
                                            list(list.Count - 1).EndTime = fRow("startTime")
                                        Else
                                            list.RemoveAt(list.Count - 1)
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If


            If alarmstatus_Door2Valid = True Then
                If Not IsDBNull(r(tablename_Door2Alarm)) Then '库门2开关状态
                    Dim alarmType As Integer = _AlarmTypeParse(tablename_Door2Alarm)
                    Dim list As List(Of AlarmEvent)
                    list = eventList(tablename_Door2Alarm)

                    If r(tablename_Door2Alarm) = g_On Then '报警
                        If list.Count <= 0 Then 'first
                            Dim headRow As DataRow = r
                            Dim hRow As DataRow = FindAlarmRealHeader(tablename_Door2Alarm, r("startTime"), cbo_rti.ProjectID.Replace("-", "_"), r("netID"), r("pageIndex"), r("RowIndex"), tempStr, g_On)
                            If hRow IsNot Nothing Then headRow = hRow

                            '检测最早时间点
                            If headRow("startTime") < earlyTime Then
                                earlyTime = headRow("startTime")
                            End If


                            AddEventToList("库门2", alarmType, headRow, list, cbo_rti)
                        Else
                            If list(list.Count - 1).EndTime <> Nothing Then
                                AddEventToList("库门2", alarmType, r, list, cbo_rti)
                            Else 'first g_off; 2008-10-31; 处理同一条记录包含多个报警开始点，为其中一个报警添加备注后，其余报警无法显示问题
                                If cRow("pageIndex") = pRow("pageIndex") AndAlso cRow("RowIndex") = pRow("RowIndex") AndAlso cRow("startTime") = pRow("startTime") Then
                                    If r("alarmType") = alarmType Then
                                        
                                    End If
                                End If
                            End If
                        End If
                    Else '正常
                        If list.Count > 0 Then
                            If list(list.Count - 1).EndTime = Nothing Then '报警未结束
                                list(list.Count - 1).EndTime = r("startTime") '设置报警结束
                            End If
                        Else
                            If i = 0 Then
                                Dim hRow As DataRow = FindAlarmRealHeader(tablename_Door2Alarm, r("startTime"), _
                                                                                cbo_rti.ProjectID.Replace("-", "_"), _
                                                                                r("netID"), _
                                                                                r("pageIndex"), _
                                                                                r("RowIndex"), _
                                                                                tempStr, _
                                                                                g_Off _
                                                            )
                                If hRow IsNot Nothing Then
                                    AddEventToList("库门2", alarmType, hRow, list, cbo_rti)
                                    'list(list.Count - 1).EndTime = r("startTime")
                                    Dim fRow As DataRow = FindAlarmRealFooter(tablename_Door2Alarm, hRow("startTime"), Me.dtpTo.Value, _
                                                                                    cbo_rti.ProjectID.Replace("-", "_"), _
                                                                                    r("netID"), _
                                                                                    hRow("pageIndex"), _
                                                                                    hRow("RowIndex"), _
                                                                                    tempStr _
                                                            )
                                    If fRow IsNot Nothing Then
                                        If fRow("startTime") >= Me.dtpFrom.Value Then '报警结束时间>=起始时间
                                            '检测最早时间点
                                            If list(list.Count - 1).StartTime < earlyTime Then
                                                earlyTime = list(list.Count - 1).StartTime
                                            End If
                                            list(list.Count - 1).EndTime = fRow("startTime")
                                        Else
                                            list.RemoveAt(list.Count - 1)
                                        End If
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If


            pRow = cRow
            bwSearch.ReportProgress((i / ds.Tables(0).Rows.Count) * 100) '报告进度
        Next

        ds.AcceptChanges()

        '检测数据完整性
        'If chkCheckAlarmDataIntegrity.Checked AndAlso dList IsNot Nothing Then
        '    If Not CheckAlarmDataIntegrity(cbo_rti.ProjectID.Replace("-", "_").Trim, cbo_rti.NetId, earlyTime, lastlyTime, dList) Then
        '        Return Nothing
        '    End If
        'End If




        If ds IsNot Nothing Then
            ds.Clear() : ds.Dispose() : ds = Nothing
        End If
        m_ailist.Clear()
        m_aiNamelist.Clear()

        'eventList.Clear() : eventList = Nothing

        Return eventList
    End Function
    Private Sub AddEventToList(ByVal [event] As String, ByVal alarmType As Integer, ByVal r As DataRow, ByVal list As Object, ByVal cbo_rti As RefTypeItem)
        If r Is Nothing Then Return
        'Dim tmpObj As Object
        Dim evn As New AlarmEvent()
        evn.StartTime = r("startTime")
        evn.AlarmType = alarmType 'r("alarmType")
        'If [event] = "断电预警" Then
        '    evn.RefName = "系统"
        'Else
        evn.RefName = cbo_rti.RefName

        ' End If

        evn.Event = [event] 'r(tablename_DoorAlarm)
        'If Not IsDBNull(r("alarmType")) AndAlso r("alarmType") = alarmType Then
        '    tmpObj = r("note")
        '    If UtilityClass.IsNotNullEmpty(tmpObj) Then evn.Note = Convert.ToString(tmpObj)
        '    tmpObj = r("reason")
        '    If UtilityClass.IsNotNullEmpty(tmpObj) Then evn.Reason = Convert.ToString(tmpObj)
        '    tmpObj = r("remark")
        '    If UtilityClass.IsNotNullEmpty(tmpObj) Then evn.Remark = Convert.ToString(tmpObj)
        '    tmpObj = r("owner")
        '    If UtilityClass.IsNotNullEmpty(tmpObj) Then evn.Owner = Convert.ToString(tmpObj)

        '    'evn.Note = Convert.ToString(r("note")) '2008.10.31
        '    'evn.Owner = Convert.ToString(r("owner"))
        'End If
        evn.ProjectID = cbo_rti.ProjectID.Replace("-", "_")
        evn.NetID = Convert.ToString(r("netID"))
        evn.PageIndex = Convert.ToString(r("pageIndex"))
        evn.RowIndex = Convert.ToString(r("RowIndex"))
        list.Add(evn)
    End Sub
    Private Function FindAlarmRealHeader(ByVal alarmName As String, ByVal startTime As DateTime, ByVal projectID As String, ByVal netID As Integer, ByVal pageIndex As Integer, ByVal rowIndex As Integer, ByVal tempStr As String, ByVal g_flag As Byte) As DataRow
        Dim lastNormalTime As DateTime = Nothing
        Dim lastAlarmTime As DateTime = Nothing
        Dim isLastNormalRow As Boolean = False
        Dim ds As DataSet = Nothing
        Dim row As DataRow = Nothing
        Dim temp As Object = Nothing

        Select Case MainForm.readConfig("SystemType")
            Case 2

                If g_flag = g_Off Then
                    temp = SqlHelper1.ExecuteScalar(String.Format("SELECT max(startTime) FROM tbcchddidata_{0} WHERE netID = '{1}' AND {2} = '0' and startTime < '{3}'", _
                                                                        projectID, netID, alarmName, UtilityClass.GetDateString(startTime)) _
                                                                        , Nothing)
                    If Not IsDBNull(temp) Then
                        lastAlarmTime = temp
                    Else
                        Return Nothing
                    End If
                Else
                    lastAlarmTime = startTime
                End If

                temp = SqlHelper1.ExecuteScalar(String.Format("SELECT max(startTime) FROM tbcchddidata_{0} WHERE netID = '{1}' AND {2} = '1' and startTime <{4} '{3}'", _
                                                    projectID, netID, alarmName, UtilityClass.GetDateString(lastAlarmTime), IIf(g_flag = g_Off, "=", String.Empty)) _
                                                    , Nothing)

                If IsDBNull(temp) Then
                    row = SqlHelper1.ExecuteDataset(String.Format("SELECT netID, pageIndex, RowIndex, startTime, {2} FROM tbcchddidata_{0} WHERE netID = '{1}' AND {2} = '0' ORDER BY startTime, pageIndex, RowIndex LIMIT 1", _
                                                    projectID, netID, alarmName), Nothing).Tables(0).Rows(0)
                Else
                    lastNormalTime = temp
                    ds = SqlHelper1.ExecuteDataset(String.Format("SELECT netID, pageIndex, RowIndex, startTime, {2} FROM tbcchddidata_{0} " & _
                                                                "WHERE netID = '{1}' " & _
                                                                "AND startTime >= '{3}' " & _
                                                                "AND startTime <= '{4}'", _
                                                                projectID, netID, alarmName, UtilityClass.GetDateString(lastNormalTime), UtilityClass.GetDateString(startTime)) _
                                                                , Nothing)

                    If ds.Tables.Count > 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
                        Dim rows As DataRowCollection = ds.Tables(0).Rows

                        For i As Integer = 0 To rows.Count - 1
                            Dim r As DataRow = rows(i)
                            If r("netID") = netID AndAlso r("pageIndex") = pageIndex AndAlso r("RowIndex") = rowIndex AndAlso r("startTime") = startTime Then
                                isLastNormalRow = True
                                Exit For '找到目标行
                            End If
                            If r(alarmName) = g_Off Then
                                If i < rows.Count - 1 AndAlso rows(i + 1)(alarmName) = g_On Then row = rows(i + 1) '记录最后一次正常的下一行记录(即:第一次报警记录)
                                'If i < rows.Count - 1 AndAlso rows(i + 1)(alarmName) = g_On Then 
                            End If
                        Next
                    End If
                End If
                '*******************************************************************************************
                '2009年06月10日 李吉鹏 修改 增加字段b.reason 添加列
                If row IsNot Nothing Then
                    ds = SqlHelper1.ExecuteDataset(String.Format(tempStr & "  FROM tbcchddidata_{0} AS a " & _
                                                                " WHERE a.netID = '{1}' AND a.pageIndex = '{2}' AND a.RowIndex = '{3}' AND a.startTime = '{4}'  ", _
                                                                projectID, _
                                                                netID, _
                                                                row("pageIndex"), _
                                                                row("RowIndex"), _
                                                                UtilityClass.GetDateString(row("startTime")), _
                                                                _AlarmTypeParse(alarmName)) _
                                                        , Nothing)
                    '***********************************************************************************************
                    If ds.Tables.Count > 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
                        Return ds.Tables(0).Rows(0)
                    End If
                End If

            Case Else


                If g_flag = g_Off Then
                    temp = SqlHelper.ExecuteScalar(String.Format("SELECT max(startTime) FROM tbcchddidata_{0} WHERE netID = '{1}' AND {2} = '0' and startTime < '{3}'", _
                                                                        projectID, netID, alarmName, UtilityClass.GetDateString(startTime)) _
                                                                        , Nothing)
                    If Not IsDBNull(temp) Then
                        lastAlarmTime = temp
                    Else
                        Return Nothing
                    End If
                Else
                    lastAlarmTime = startTime
                End If

                temp = SqlHelper.ExecuteScalar(String.Format("SELECT max(startTime) FROM tbcchddidata_{0} WHERE netID = '{1}' AND {2} = '1' and startTime <{4} '{3}'", _
                                                    projectID, netID, alarmName, UtilityClass.GetDateString(lastAlarmTime), IIf(g_flag = g_Off, "=", String.Empty)) _
                                                    , Nothing)

                If IsDBNull(temp) Then
                    row = SqlHelper.ExecuteDataset(String.Format("SELECT netID, pageIndex, RowIndex, startTime, {2} FROM tbcchddidata_{0} WHERE netID = '{1}' AND {2} = '0' ORDER BY startTime, pageIndex, RowIndex LIMIT 1", _
                                                    projectID, netID, alarmName), Nothing).Tables(0).Rows(0)
                Else
                    lastNormalTime = temp
                    ds = SqlHelper.ExecuteDataset(String.Format("SELECT netID, pageIndex, RowIndex, startTime, {2} FROM tbcchddidata_{0} " & _
                                                                "WHERE netID = '{1}' " & _
                                                                "AND startTime >= '{3}' " & _
                                                                "AND startTime <= '{4}'", _
                                                                projectID, netID, alarmName, UtilityClass.GetDateString(lastNormalTime), UtilityClass.GetDateString(startTime)) _
                                                                , Nothing)

                    If ds.Tables.Count > 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
                        Dim rows As DataRowCollection = ds.Tables(0).Rows

                        For i As Integer = 0 To rows.Count - 1
                            Dim r As DataRow = rows(i)
                            If r("netID") = netID AndAlso r("pageIndex") = pageIndex AndAlso r("RowIndex") = rowIndex AndAlso r("startTime") = startTime Then
                                isLastNormalRow = True
                                Exit For '找到目标行
                            End If
                            If r(alarmName) = g_Off Then
                                If i < rows.Count - 1 AndAlso rows(i + 1)(alarmName) = g_On Then row = rows(i + 1) '记录最后一次正常的下一行记录(即:第一次报警记录)
                                'If i < rows.Count - 1 AndAlso rows(i + 1)(alarmName) = g_On Then 
                            End If
                        Next
                    End If
                End If
                '*******************************************************************************************
                '2009年06月10日 李吉鹏 修改 增加字段b.reason 添加列
                If row IsNot Nothing Then
                    ds = SqlHelper.ExecuteDataset(String.Format(tempStr & "  FROM tbcchddidata_{0} AS a " & _
                                                                " WHERE a.netID = '{1}' AND a.pageIndex = '{2}' AND a.RowIndex = '{3}' AND a.startTime = '{4}'  ", _
                                                                projectID, _
                                                                netID, _
                                                                row("pageIndex"), _
                                                                row("RowIndex"), _
                                                                UtilityClass.GetDateString(row("startTime")), _
                                                                _AlarmTypeParse(alarmName)) _
                                                        , Nothing)
                    '***********************************************************************************************
                    If ds.Tables.Count > 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
                        Return ds.Tables(0).Rows(0)
                    End If
                End If


        End Select


       

        Return Nothing
    End Function
    Private Function FindAlarmRealFooter(ByVal alarmName As String, ByVal startTime As DateTime, ByVal endTime As DateTime, ByVal projectID As String, ByVal netID As Integer, ByVal pageIndex As Integer, ByVal rowIndex As Integer, ByVal tempStr As String) As DataRow
        Dim ds As DataSet
        Dim str As String

        str = String.Format("SELECT netID, pageIndex, RowIndex, startTime FROM tbcchddidata_{0} " & _
                            " WHERE netID = '{1}' AND ((startTime = '{2}' AND (pageIndex > '{5}' OR RowIndex > '{6}')) OR (startTime > '{2}')) AND startTime <= '{3}' AND {4} = '1' ORDER BY startTime LIMIT 1", _
                            projectID, netID, UtilityClass.GetDateString(startTime), UtilityClass.GetDateString(endTime), alarmName, pageIndex, rowIndex)

        ' ds = SqlHelper.ExecuteDataset(str, Nothing)
        Select Case MainForm.readConfig("SystemType")
            Case 2
                ds = SqlHelper1.ExecuteDataset(str, Nothing)
            Case Else
                ds = SqlHelper.ExecuteDataset(str, Nothing)
        End Select

        If ds.Tables.Count > 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
            Return ds.Tables(0).Rows(0)
        End If

        Return Nothing
    End Function
#Region "HIDE"
   
#End Region
    Private Function CheckAlarmDataIntegrity(ByVal projectID As String, ByVal netID As Integer, ByVal startTime As DateTime, ByVal endTime As DateTime, ByVal rList As List(Of AlarmEvent)) As Boolean

        Dim startRow, endRow, startPage, endPage As Integer
        startRow = 0 : startPage = 3751 : endPage = 3950
        Dim pPageIndex, pRowIndex, cPageIndex, cRowIndex As Integer
        pPageIndex = -1 : pRowIndex = -1
        'Dim pPageStartTime, cPageStartTime As DateTime
        Dim cStartTime, pStartTime As DateTime
        'Dim rList As New List(Of AlarmEvent)()
        Dim ds As DataSet
        Dim devtype As Integer
        devtype = DevTypeService.GetdevType(projectID, netID)
        Select Case devtype
            Case 1
                endRow = 10
            Case 16
                endRow = 4
        End Select

        Select Case MainForm.readConfig("SystemType")
            Case 2
                ds = SqlHelper1.ExecuteDataset(String.Format("SELECT pageStartTime, pageIndex, rowIndex, startTime FROM tbccHDAlarmData_{0} WHERE netID = '{1}' AND startTime >= '{2}' AND startTime <= '{3}' ORDER BY StartTime ASC, pageIndex ASC, rowIndex ASC", _
                                                    projectID, netID, UtilityClass.GetDateString(startTime), UtilityClass.GetDateString(endTime)), Nothing)

            Case Else
                ds = SqlHelper.ExecuteDataset(String.Format("SELECT pageStartTime, pageIndex, rowIndex, startTime FROM tbccHDAlarmData_{0} WHERE netID = '{1}' AND startTime >= '{2}' AND startTime <= '{3}' ORDER BY StartTime ASC, pageIndex ASC, rowIndex ASC", _
                                                    projectID, netID, UtilityClass.GetDateString(startTime), UtilityClass.GetDateString(endTime)), Nothing)


        End Select

        
        If ds.Tables.Count > 0 AndAlso ds.Tables(0).Rows.Count > 0 Then
            Dim rows As DataRowCollection = ds.Tables(0).Rows

            For i As Integer = 0 To rows.Count - 1
                'If bwSearch.CancellationPending Then Exit For
                Dim row As DataRow = rows(i)
                cPageIndex = row("pageIndex")
                cRowIndex = row("rowIndex")
                cStartTime = row("startTime")

                If pPageIndex <> -1 AndAlso pRowIndex <> -1 Then 'Skip First Row

                    '跳过同一行记录
                    If cPageIndex = pPageIndex AndAlso cRowIndex = pRowIndex AndAlso cStartTime = pStartTime Then
                        Continue For
                    End If

                    If cRowIndex = startRow Then '下一页第一行
                        If pRowIndex = endRow Then '确定上一页行是末尾行号
                            If cPageIndex = startPage Then '第一页
                                If pPageIndex = endPage Then '确定上一页是页末尾号
                                    If rList.Count > 0 Then
                                        If rList(rList.Count - 1).EndTime = Nothing Then
                                            rList(rList.Count - 1).EndTime = cStartTime
                                        End If
                                    End If
                                Else '当前页与上一页不连续
                                    Dim ae As New AlarmEvent()
                                    ae.StartTime = pStartTime
                                    rList.Add(ae)
                                End If
                            Else
                                If cPageIndex = pPageIndex + 1 Then '当前页与上一页保持连续
                                    If rList.Count > 0 Then
                                        If rList(rList.Count - 1).EndTime = Nothing Then
                                            rList(rList.Count - 1).EndTime = cStartTime
                                        End If
                                    End If
                                Else '当前页与上一页不连续
                                    Dim ae As New AlarmEvent()
                                    ae.StartTime = pStartTime
                                    rList.Add(ae)
                                End If
                            End If
                        Else '当前记录与上一条不连续
                            Dim ae As New AlarmEvent()
                            ae.StartTime = pStartTime
                            rList.Add(ae)
                        End If
                    Else
                        If cPageIndex = pPageIndex AndAlso cRowIndex = pRowIndex + 1 Then '当前记录与上一条保持连续
                            If rList.Count > 0 Then
                                If rList(rList.Count - 1).EndTime = Nothing Then
                                    rList(rList.Count - 1).EndTime = cStartTime
                                End If
                            End If
                        Else '当前记录与上一条不连续
                            Dim ae As New AlarmEvent()
                            ae.StartTime = pStartTime
                            rList.Add(ae)
                        End If
                    End If
                End If

                pPageIndex = cPageIndex
                pRowIndex = cRowIndex
                pStartTime = cStartTime
                'bwSearch.ReportProgress((i / rows.Count) * 100) '报告进度
            Next
        End If

        Return Not rList.Count
    End Function

    ''' <summary>
    ''' 检查时间范围是否合法
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckValidate() As Boolean
        If Me.dtpTo.Value < Me.dtpFrom.Value Then
            msg.ShowWarning("起始时间不能大于终止时间")
            Me.dtpFrom.Focus()
            Return False
        End If


        If cboRef.SelectedIndex = -1 Then
            msg.ShowWarning("请选择冷库")
            Me.cboRef.Focus()
            Return False
        End If

        Return True
    End Function

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        Me.Cursor = Cursors.WaitCursor
        sender.Enabled = False
        Print()
        sender.Enabled = True
        Me.Cursor = Cursors.Default
    End Sub

    'Dim cols(100) As String
    Dim headers(100) As String

    Private Sub Print()
        'has data
        Dim dt As DataGridView
        dt = Me.DataGridView1
        If dt Is Nothing OrElse dt.Rows.Count = 0 Then
            msg.Show("没有数据")
            Exit Sub
        End If

        'Excel object
        Dim objExcel As New Excel.Application
        Dim wb As Excel.Workbook = objExcel.Workbooks.Add()

        'ReDim Preserve cols(100)
        ReDim headers(100)

        'Get col pro name and head text
        Dim index As Integer = 0
        'cols(index) = "序号"
        'headers(index) = "序号"
        For i As Integer = 0 To Me.DataGridView1.Columns.Count - 1
            If Me.DataGridView1.Columns(i).Visible Then
                'cols(index) = Me.DataGridView1.Columns(i).DataPropertyName
                headers(index) = Me.DataGridView1.Columns(i).HeaderText
                index += 1
            End If
        Next
        'headers(index + 1) = "处理结果"
        'headers(index + 2) = "负责人"

        'ReDim Preserve cols(index)

        Dim values(dt.Rows.Count, index) As Object

        'Set headers
        For j As Integer = 0 To index '序号
            values(0, j) = headers(j)
        Next

        'Set values
        For i As Integer = 0 To dt.Rows.Count - 1
            Dim r As DataGridViewRow = dt.Rows(i)
            'values(i + 1, 0) = i + 1
            For j As Integer = 0 To index - 1
                values(i + 1, j) = r.Cells(j).Value 'j+1序号
            Next
        Next

        'Print
        Dim pwd As String = System.Guid.NewGuid().ToString()
        Try
            objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, index + 1)).Value2 = values 'col+1序号

            'Set format
            objExcel.Columns("A:AA").Select()
            objExcel.Selection.HorizontalAlignment = Excel.Constants.xlCenter
            objExcel.Selection.Font.Size = 10
            objExcel.Selection.ColumnWidth = 10

            Dim selectRange As Excel.Range
            '序号
            selectRange = objExcel.Range("A1", "A" & (dt.Rows.Count + 1))
            selectRange.ColumnWidth = 3


            '开始结束时间
            selectRange = objExcel.Range("B1", objExcel.Cells(dt.Rows.Count + 1, 3))
            selectRange.ColumnWidth = 19
            selectRange.NumberFormatLocal = "yyyy-mm-dd hh:mm:ss"


            If (Me.cboRef.SelectedIndex = 0) Then
                '冷库
                selectRange = objExcel.Range("D:D")
                selectRange.ColumnWidth = 10
                selectRange.WrapText = True

                '事件
                selectRange = objExcel.Range("E:E")
                selectRange.ColumnWidth = 10
                selectRange.WrapText = True
                '**********************************************
                '事故原因
                '2009年06月11日 李吉鹏 增加
                selectRange = objExcel.Range("F:F")
                selectRange.ColumnWidth = 15
                selectRange.WrapText = True

                '处理结果
                selectRange = objExcel.Range("G:G")
                selectRange.ColumnWidth = 15
                selectRange.WrapText = True

                selectRange = objExcel.Range("H:H")
                selectRange.ColumnWidth = 15
                selectRange.WrapText = True
                selectRange = objExcel.Range("I:I")
                selectRange.ColumnWidth = 15
                selectRange.WrapText = True
            Else
                '事件
                selectRange = objExcel.Range("D:D")
                selectRange.ColumnWidth = 15
                selectRange.WrapText = True
                '**********************************************
                '2009年06月11日 李吉鹏 增加
                '事故原因
                selectRange = objExcel.Range("E:E")
                selectRange.ColumnWidth = 18
                selectRange.WrapText = True

                '处理结果
                selectRange = objExcel.Range("F:F")
                selectRange.ColumnWidth = 17
                selectRange.WrapText = True

                selectRange = objExcel.Range("G:G")
                selectRange.ColumnWidth = 17
                selectRange.WrapText = True
                selectRange = objExcel.Range("H:H")
                selectRange.ColumnWidth = 17
                selectRange.WrapText = True

            End If

            ''负责人
            'selectRange = objExcel.Range("F:F")
            'selectRange.ColumnWidth = 10

            '设置边框
            Dim range As Excel.Range = objExcel.Range(objExcel.Cells(1, 1), objExcel.Cells(dt.Rows.Count + 1, index))
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeBottom).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeLeft).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeRight).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlEdgeTop).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideHorizontal).LineStyle = Excel.XlLineStyle.xlContinuous
            range.Borders.Item(Excel.XlBordersIndex.xlInsideVertical).LineStyle = Excel.XlLineStyle.xlContinuous

            'objExcel.Columns.AutoFit()

            '设置保护
            Try
                objExcel.ActiveSheet.Protect(pwd, _
                            AllowFormattingCells:=False, _
                            AllowFormattingColumns:=False, _
                            AllowFormattingRows:=False, _
                            AllowInsertingColumns:=False, _
                            AllowInsertingRows:=False, _
                            AllowInsertingHyperlinks:=False, _
                            AllowDeletingColumns:=False, _
                            AllowDeletingRows:=False _
                )
            Catch ex As Exception
                objExcel.ActiveSheet.Protect(pwd)
            End Try

            'Set page
            Dim ws As Excel.Worksheet = objExcel.ActiveSheet
            With ws.PageSetup
                '.LeftHeader = "&G" & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                .LeftHeader = vbCr & vbCr & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                .CenterHeader = String.Format("&""宋体,加粗""&28 {0}报警查询 ", Me.cboRef.Text)
                .RightHeader = vbCr & vbCr & vbCr & "共&N页 第&P页"
                .LeftFooter = "养护员："
                .CenterFooter = ""
                .RightFooter = "打印日期：&D &T"
                .LeftMargin = objExcel.Application.InchesToPoints(0.6)
                .RightMargin = objExcel.Application.InchesToPoints(0.4)
                .TopMargin = objExcel.Application.InchesToPoints(1.08)
                .BottomMargin = objExcel.Application.InchesToPoints(0.68)
                .HeaderMargin = objExcel.Application.InchesToPoints(0.22)
                .FooterMargin = objExcel.Application.InchesToPoints(0.5)
                .PrintHeadings = False
                .PrintGridlines = True
                '.PrintComments = objExcel.xlPrintNoComments
                ''.PrintQuality = 300
                .CenterHorizontally = False
                .CenterVertically = False
                '.Orientation = objExcel.xlPortrait
                .Draft = False
                '.PaperSize = Excel.XlPaperSize.xlPaperA4
                .Orientation = Excel.XlPageOrientation.xlLandscape '横向打印 'xlPortrait '纵向打印
                '.FirstPageNumber = objExcel.xlAutomatic
                '.Order = objExcel.xlDownThenOver
                '.BlackAndWhite = False
                .Zoom = 100
                '.PrintErrors = objExcel.xlPrintErrorsDisplayed

                '.PrintArea = "A1:U" & bRow
                .FitToPagesWide = 1
                .FitToPagesTall = 1
                .PrintTitleRows = "$1:$1"

                'Try

                '    With .LeftHeaderPicture
                '        .Filename = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) & "\ClientLogo.jpg"
                '        .Height = 68
                '        .Width = 68
                '        .LockAspectRatio = 0
                '    End With

                'Catch ex As Exception
                '    .LeftHeader = vbCr & vbCr & vbCr & String.Format(" 监控时间：{0}至{1}", Me.dtpFrom.Value, Me.dtpTo.Value) & vbCr & vbCr
                '    Debug.WriteLine("页眉图片" & ex.ToString())
                'End Try

            End With

            'Show Print
            objExcel.Visible = True
            objExcel.ActiveWindow.SelectedSheets.PrintPreview()

        Catch ex As Exception
            Debug.WriteLine("打印错误" & ex.ToString())
            msg.Show(ex.Message)
        Finally
            Try
                If objExcel.ActiveWindow.View = Excel.XlWindowView.xlNormalView Then '分页预览
                    'objExcel.ActiveSheet.Unprotect(pwd)
                    wb.Close(False, False)
                    objExcel.DisplayAlerts = False
                    objExcel.Quit()
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(wb)
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(objExcel)
                    wb = Nothing
                    objExcel = Nothing
                    GC.Collect()
                End If
            Catch ex As Exception
                Debug.WriteLine(ex.ToString())
            End Try

        End Try
    End Sub


    Private Sub cboRef_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboRef.SelectedIndexChanged
        If CType(sender, ComboBox).SelectedIndex <> -1 Then
            btnRefresh.Enabled = True
            btnPrint.Enabled = False
        End If
    End Sub

    Private Class AlarmEvent
        Public ProjectID As String
        Public NetID As Integer
        Public PageIndex As Integer
        Public RowIndex As Integer
        Public StartTime As DateTime = Nothing
        Public EndTime As DateTime = Nothing
        Public RefName As String
        Public [Event] As String = Nothing
        Public AlarmType As Integer
        Public Reason As String = Nothing
        Public Remark As String = Nothing
        Public Note As String = Nothing
        Public Owner As String = Nothing
    End Class

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSave.Click
        Me.Cursor = Cursors.WaitCursor
        sender.Enabled = False
        If SaveRemark() Then
            rowChangeList.Clear()
            msg.Show("保存成功")
        Else
            msg.ShowError("保存失败")
            sender.Enabled = True
        End If
        Me.Cursor = Cursors.Default
    End Sub

    Private Function SaveRemark() As Boolean
        Const PROJECTID = "ProjectID"
        Const NETID = "NetID"
        Const PAGEINDEX = "PageIndex"
        Const ROWINDEX = "RowIndex"
        Const STARTTIME = "startTime"
        Const ALARMTYPE = "AlarmType"
        Const NOTE = "note"
        '**********************************************************************
        Const REMARK = "remark"
        Const REASON = "reason"
        Const OWNER = "owner"
        Dim strSql As String = ""

        Select Case MainForm.readConfig("SystemType")
            Case 2

                For i As Integer = 0 To rowChangeList.Count - 1
                    Dim row As DataGridViewRow = rowChangeList(i)

                    If String.IsNullOrEmpty(row.Cells(NOTE).Value) AndAlso String.IsNullOrEmpty(row.Cells(OWNER).Value) AndAlso String.IsNullOrEmpty(row.Cells(REASON).Value) Then '为空值时
                        SqlHelper1.ExecuteNonQuery(String.Format("DELETE FROM tbccHDAlarmDoc WHERE projectid = '{0}' AND netID = '{1}' AND pageIndex = '{2}' AND RowIndex = '{3}' AND startTime = '{4}' AND alarmType = '{5}'", _
                                                                                row.Cells(PROJECTID).Value, _
                                                                                row.Cells(NETID).Value, _
                                                                                row.Cells(PAGEINDEX).Value, _
                                                                                row.Cells(ROWINDEX).Value, _
                                                                                UtilityClass.GetDateString(CDate(row.Cells(STARTTIME).Value)), _
                                                                                row.Cells(ALARMTYPE).Value _
                                                                    ), Nothing)
                        SaveRemark = True
                    Else

                        Dim p(9) As MySql.Data.MySqlClient.MySqlParameter
                        For j As Integer = 0 To p.Length - 1
                            p(j) = New MySql.Data.MySqlClient.MySqlParameter()
                            p(j).ParameterName = "p" + j.ToString
                        Next j
                        '*************************************************************************************
                        p(0).Value = row.Cells(REMARK).Value
                        p(1).Value = row.Cells(REASON).Value
                        p(2).Value = row.Cells(NOTE).Value
                        p(3).Value = row.Cells(OWNER).Value
                        p(4).Value = row.Cells(PROJECTID).Value
                        p(5).Value = row.Cells(NETID).Value
                        p(6).Value = row.Cells(PAGEINDEX).Value
                        p(7).Value = row.Cells(ROWINDEX).Value
                        p(8).Value = UtilityClass.GetDateString(CDate(row.Cells(STARTTIME).Value))
                        p(9).Value = row.Cells(ALARMTYPE).Value

                        If SqlHelper1.ExecuteScalar(String.Format("SELECT COUNT(*) FROM tbccHDAlarmDoc WHERE projectid = '{0}' AND netID = '{1}' AND pageIndex = '{2}' AND RowIndex = '{3}' AND startTime = '{4}' AND alarmType = '{5}'", _
                                                                row.Cells(PROJECTID).Value, _
                                                                row.Cells(NETID).Value, _
                                                                row.Cells(PAGEINDEX).Value, _
                                                                row.Cells(ROWINDEX).Value, _
                                                                UtilityClass.GetDateString(CDate(row.Cells(STARTTIME).Value)), _
                                                                row.Cells(ALARMTYPE).Value _
                                                    ), Nothing) <= 0 Then
                            '**********************************************************************************************************


                            SaveRemark = SqlHelper1.ExecuteNonQuery("INSERT INTO tbccHDAlarmDoc(remark,reason,note,owner,projectid,netID,pageIndex,RowIndex,startTime,alarmtype) VALUES(?p0,?p1,?p2,?p3,?p4,?p5,?p6,?p7,?p8,?p9)", p)
                        Else
                            SaveRemark = SqlHelper1.ExecuteNonQuery("UPDATE tbccHDAlarmDoc SET remark=?p0, reason=?p1,note=?p2, owner=?p3 WHERE projectid=?p4 AND netID=?p5 AND pageIndex=?p6 AND RowIndex=?p7 AND startTime=?p8 AND alarmtype=?p9", p)
                        End If

                    End If

                Next

            Case Else

                For i As Integer = 0 To rowChangeList.Count - 1
                    Dim row As DataGridViewRow = rowChangeList(i)

                    If String.IsNullOrEmpty(row.Cells(NOTE).Value) AndAlso String.IsNullOrEmpty(row.Cells(OWNER).Value) AndAlso String.IsNullOrEmpty(row.Cells(REASON).Value) Then '为空值时
                        SqlHelper.ExecuteNonQuery(String.Format("DELETE FROM tbccHDAlarmDoc WHERE projectid = '{0}' AND netID = '{1}' AND pageIndex = '{2}' AND RowIndex = '{3}' AND startTime = '{4}' AND alarmType = '{5}'", _
                                                                                row.Cells(PROJECTID).Value, _
                                                                                row.Cells(NETID).Value, _
                                                                                row.Cells(PAGEINDEX).Value, _
                                                                                row.Cells(ROWINDEX).Value, _
                                                                                UtilityClass.GetDateString(CDate(row.Cells(STARTTIME).Value)), _
                                                                                row.Cells(ALARMTYPE).Value _
                                                                    ), Nothing)
                        SaveRemark = True
                    Else

                        Dim p(9) As MySql.Data.MySqlClient.MySqlParameter
                        For j As Integer = 0 To p.Length - 1
                            p(j) = New MySql.Data.MySqlClient.MySqlParameter()
                            p(j).ParameterName = "p" + j.ToString
                        Next j
                        '*************************************************************************************
                        p(0).Value = row.Cells(REMARK).Value
                        p(1).Value = row.Cells(REASON).Value
                        p(2).Value = row.Cells(NOTE).Value
                        p(3).Value = row.Cells(OWNER).Value
                        p(4).Value = row.Cells(PROJECTID).Value
                        p(5).Value = row.Cells(NETID).Value
                        p(6).Value = row.Cells(PAGEINDEX).Value
                        p(7).Value = row.Cells(ROWINDEX).Value
                        p(8).Value = UtilityClass.GetDateString(CDate(row.Cells(STARTTIME).Value))
                        p(9).Value = row.Cells(ALARMTYPE).Value

                        If SqlHelper.ExecuteScalar(String.Format("SELECT COUNT(*) FROM tbccHDAlarmDoc WHERE projectid = '{0}' AND netID = '{1}' AND pageIndex = '{2}' AND RowIndex = '{3}' AND startTime = '{4}' AND alarmType = '{5}'", _
                                                                row.Cells(PROJECTID).Value, _
                                                                row.Cells(NETID).Value, _
                                                                row.Cells(PAGEINDEX).Value, _
                                                                row.Cells(ROWINDEX).Value, _
                                                                UtilityClass.GetDateString(CDate(row.Cells(STARTTIME).Value)), _
                                                                row.Cells(ALARMTYPE).Value _
                                                    ), Nothing) <= 0 Then
                            '**********************************************************************************************************


                            SaveRemark = SqlHelper.ExecuteNonQuery("INSERT INTO tbccHDAlarmDoc(remark,reason,note,owner,projectid,netID,pageIndex,RowIndex,startTime,alarmtype) VALUES(?p0,?p1,?p2,?p3,?p4,?p5,?p6,?p7,?p8,?p9)", p)
                        Else
                            SaveRemark = SqlHelper.ExecuteNonQuery("UPDATE tbccHDAlarmDoc SET remark=?p0, reason=?p1,note=?p2, owner=?p3 WHERE projectid=?p4 AND netID=?p5 AND pageIndex=?p6 AND RowIndex=?p7 AND startTime=?p8 AND alarmtype=?p9", p)
                        End If

                    End If

                Next

        End Select

       

    End Function

    Private isLoading As Boolean = False
    Private isSorting As Boolean = False
    Private rowChangeList As New List(Of DataGridViewRow)
    Private Sub DataGridView1_CellValueChanged(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
        If Not isSorting AndAlso Not isLoading AndAlso e.RowIndex >= 0 Then
            Me.btnSave.Enabled = True
            Dim row As DataGridViewRow = DataGridView1.Rows(e.RowIndex)

            If Not rowChangeList.Contains(row) Then
                rowChangeList.Add(row)
            End If
        End If
    End Sub

    Private Sub HDDocAlarmForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If rowChangeList.Count > 0 Then
            Select Case ShowSaveConfim()
                Case Windows.Forms.DialogResult.Yes
                    btnSave_Click(btnSave, e)
                    e.Cancel = False
                    DisposeBackWorker()
                Case Windows.Forms.DialogResult.No
                    e.Cancel = False
                    DisposeBackWorker()
                Case Windows.Forms.DialogResult.Cancel
                    e.Cancel = True
            End Select
        End If
    End Sub
    Private Sub DisposeBackWorker()
        If Me.bwSearch IsNot Nothing Then
            Me.bwSearch.CancelAsync()
            Me.bwSearch.Dispose() : Me.bwSearch = Nothing
        End If
        GC.Collect()
    End Sub

    Private Function ShowSaveConfim() As DialogResult
        Return MessageBox.Show("记录已经修改, 是否要保存", Me.Text, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information)
    End Function

    Private Sub DataGridView1_ColumnHeaderMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.ColumnHeaderMouseClick
        RefreshDataGridViewNo()
    End Sub

    Private _isIntegrity As Boolean
    Private Delegate Sub VoidMethodHandler(ByVal obj As Object)
    Private Sub bwSearch_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bwSearch.DoWork
        Dim bwParam As ArrayList = e.Argument
        Dim rStr As String = String.Empty
        e.Result = New Object() {0, Nothing, False}
        _isIntegrity = True

        Try

            For Each p As Object() In bwParam
                If bwSearch.CancellationPending Then
                    Exit For
                End If
                Dim rti As RefTypeItem = p(0)
                Dim dList As List(Of AlarmEvent) = p(1)
                Dim eventList As Hashtable

                'Me.lblSearchState.Text = String.Format("正在查询{0}历史报警数据……", rti.RefName)
                eventList = RefreshDataHelper(rti, dList)

                If dList IsNot Nothing AndAlso dList.Count > 0 Then
                    _isIntegrity = False '数据残缺
                    rStr &= rti.NetId & "号设备报警数据残缺，请重新上传数据：" & vbCrLf
                    For Each evn As AlarmEvent In dList
                        rStr &= IIf(evn.StartTime = DateTime.MinValue, "未知", evn.StartTime.ToString("yyyy-MM-dd HH:mm")) & " - " & IIf(evn.EndTime = DateTime.MinValue, dtpTo.Value.ToString("yyyy-MM-dd HH:mm"), evn.EndTime.ToString("yyyy-MM-dd HH:mm")) & vbCrLf
                    Next
                    rStr &= vbCrLf
                End If

                If _isIntegrity Then
                    If eventList IsNot Nothing Then
                        If Me.InvokeRequired Then
                            Me.Invoke(New VoidMethodHandler(AddressOf AddEventToGridView), eventList)
                        Else
                            AddEventToGridView(eventList)
                        End If
                    End If
                End If

                '清除报警事件列表, 数据残缺列表
                eventList.Clear()
                If dList IsNot Nothing Then dList.Clear()
                'eventList = Nothing : dList = Nothing
            Next

        Catch ex As Exception
            Debug.Write("HDDocAlarmForm.bwSearch_DoWork()")
        End Try

        e.Result(0) = Me.DataGridView1.Rows.Count
        e.Result(1) = rStr
        e.Result(2) = bwSearch.CancellationPending

    End Sub

    Private Sub bwSearch_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bwSearch.ProgressChanged
        pbSearch.Value = e.ProgressPercentage
    End Sub

    Private Sub bwSearch_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bwSearch.RunWorkerCompleted
        If Me.InvokeRequired Then
            Me.Invoke(New VoidMethodHandler(AddressOf SearchCompleted), e.Result)
        Else
            SearchCompleted(e.Result)
        End If

        AfterRefreshControlState()
        GC.Collect()

        If e.Result(2) Then
            msg.Show("操作已取消")
        End If
    End Sub
    Private Sub AddEventToGridView(ByVal obj As Object)
        Dim eventList = obj
        '将警报事件添加至DataGridView
        'Dim sNo As Integer = 0
        For Each list As List(Of AlarmEvent) In eventList.Values
            For Each evn As AlarmEvent In list
                Dim row As New DataGridViewRow()
                Dim cell As DataGridViewTextBoxCell

                'no
                cell = New DataGridViewTextBoxCell()
                row.Cells.Add(cell)

                If (Me.cboRef.SelectedIndex = 0) Then
                    'ref name
                    cell = New DataGridViewTextBoxCell()
                    cell.Value = evn.RefName
                    row.Cells.Add(cell)
                End If

                'event
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.Event
                row.Cells.Add(cell)

                'start date
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.StartTime.ToString("yyyy-MM-dd HH:mm:ss")
                row.Cells.Add(cell)

                'end date
                cell = New DataGridViewTextBoxCell()
                If evn.EndTime = DateTime.MinValue Then '2008.1.31
                    cell.Value = "未关闭"
                Else
                    cell.Value = evn.EndTime.ToString("yyyy-MM-dd HH:mm:ss")
                End If
                row.Cells.Add(cell)

               
                '*********************************
                'reason
                '2009年06月10日 李吉鹏 修改
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.Reason
                row.Cells.Add(cell)
                '******************************************


                'note; 2008.10.31
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.Note
                row.Cells.Add(cell)

                'owner; 2008.10.31
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.Owner
                row.Cells.Add(cell)
                '*********************************
                'remark
                '2009年08月11日 李吉鹏 修改
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.Remark
                row.Cells.Add(cell)
                '******************************************

                'projectid; 2008.10.31
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.ProjectID
                row.Cells.Add(cell)

                'netID; 2008.10.31
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.NetID
                row.Cells.Add(cell)

                'pageIndex; 2008.10.31
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.PageIndex
                row.Cells.Add(cell)

                'RowIndex; 2008.10.31
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.RowIndex
                row.Cells.Add(cell)

                'alarmType; 2008.10.31
                cell = New DataGridViewTextBoxCell()
                cell.Value = evn.AlarmType
                row.Cells.Add(cell)

                Me.DataGridView1.Rows.Add(row)
            Next
        Next
    End Sub
    Private Sub SearchCompleted(ByVal result As Object)
        Dim str As String = result(1)
        Me.pnlSearch.Visible = False

        If _isIntegrity Then
            If result(0) > 0 Then
                SetDataGridViewColumnVisible(True)
                Me.DataGridView1.Sort(Me.DataGridView1.Columns("startTime"), System.ComponentModel.ListSortDirection.Ascending)
                RefreshDataGridViewNo()
                Me.btnPrint.Enabled = True
            ElseIf Not result(2) Then '无数据处理(排除取消操作)
                Me.DataGridView1.Rows.Clear()
                Me.DataGridView1.Columns.Clear()
                Me.btnPrint.Enabled = False
                msg.Show("指定时间范围没有数据,请重新设置")
            End If
        Else '数据残缺处理
            Me.DataGridView1.Rows.Clear()
            Me.DataGridView1.Columns.Clear()
            msg.ShowWarning(str)
        End If
    End Sub
    Private Sub AddDataGridViewColumns()
        Dim m_index As Integer

        '添加DataGridView列
        m_index = Me.DataGridView1.Columns.Add("NO", "序号")
        Me.DataGridView1.Columns(m_index).SortMode = DataGridViewColumnSortMode.NotSortable
        Me.DataGridView1.Columns(m_index).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        Me.DataGridView1.Columns(m_index).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        Me.DataGridView1.Columns(m_index).DefaultCellStyle.BackColor = System.Drawing.SystemColors.Control
        Me.DataGridView1.Columns(m_index).Width = 50
        Me.DataGridView1.Columns(m_index).ReadOnly = True
        If (Me.cboRef.SelectedIndex = 0) Then
            m_index = Me.DataGridView1.Columns.Add("RefName", "冷库")
            Me.DataGridView1.Columns(m_index).Width = 100
            Me.DataGridView1.Columns(m_index).ReadOnly = True
            'Me.DataGridView1.Columns(m_index).DataPropertyName = "RefName"
        End If
        m_index = Me.DataGridView1.Columns.Add("event", "库门")
        Me.DataGridView1.Columns(m_index).Width = 100
        Me.DataGridView1.Columns(m_index).ReadOnly = True

        m_index = Me.DataGridView1.Columns.Add("startTime", "开启时间")
        Me.DataGridView1.Columns(m_index).Width = 150
        Me.DataGridView1.Columns(m_index).ReadOnly = True
        'Me.DataGridView1.Columns(m_index).DataPropertyName = "startTime"
        m_index = Me.DataGridView1.Columns.Add("endTime", "关闭时间")
        Me.DataGridView1.Columns(m_index).Width = 150
        Me.DataGridView1.Columns(m_index).ReadOnly = True
        'Me.DataGridView1.Columns(m_index).DataPropertyName = "endTime"
        
        'Me.DataGridView1.Columns(m_index).DataPropertyName = "event"
        '***********************************************************************
        '2009年06月10日 李吉鹏 添加
        m_index = Me.DataGridView1.Columns.Add("reason", "报警原因")
        Me.DataGridView1.Columns(m_index).Visible = False
        'Me.DataGridView1.Columns(m_index).DataPropertyName = "note"
        Me.DataGridView1.Columns(m_index).ReadOnly = False
        Me.DataGridView1.Columns(m_index).Width = 100
        '*********************************************************************
        m_index = Me.DataGridView1.Columns.Add("note", "采取措施")
        Me.DataGridView1.Columns(m_index).Visible = False
        'Me.DataGridView1.Columns(m_index).DataPropertyName = "note"
        Me.DataGridView1.Columns(m_index).ReadOnly = False
        Me.DataGridView1.Columns(m_index).Width = 150
        m_index = Me.DataGridView1.Columns.Add("owner", "责任人")
        Me.DataGridView1.Columns(m_index).Visible = False
        'Me.DataGridView1.Columns(m_index).DataPropertyName = "owner"
        Me.DataGridView1.Columns(m_index).Width = 150
        Me.DataGridView1.Columns(m_index).ReadOnly = False
        m_index = Me.DataGridView1.Columns.Add("remark", "备注")
        Me.DataGridView1.Columns(m_index).Visible = False
        'Me.DataGridView1.Columns(m_index).DataPropertyName = "owner"
        Me.DataGridView1.Columns(m_index).Width = 150
        Me.DataGridView1.Columns(m_index).ReadOnly = False
        m_index = Me.DataGridView1.Columns.Add("ProjectID", "ProjectID")
        Me.DataGridView1.Columns(m_index).Visible = False
        Me.DataGridView1.Columns(m_index).ReadOnly = True
        m_index = Me.DataGridView1.Columns.Add("NetID", "NetID")
        Me.DataGridView1.Columns(m_index).Visible = False
        Me.DataGridView1.Columns(m_index).ReadOnly = True
        m_index = Me.DataGridView1.Columns.Add("PageIndex", "PageIndex")
        Me.DataGridView1.Columns(m_index).Visible = False
        Me.DataGridView1.Columns(m_index).ReadOnly = True
        m_index = Me.DataGridView1.Columns.Add("RowIndex", "RowIndex")
        Me.DataGridView1.Columns(m_index).Visible = False
        Me.DataGridView1.Columns(m_index).ReadOnly = True
        m_index = Me.DataGridView1.Columns.Add("AlarmType", "AlarmType")
        Me.DataGridView1.Columns(m_index).Visible = False
        Me.DataGridView1.Columns(m_index).ReadOnly = True
    End Sub
    Private Sub SetDataGridViewColumnVisible(ByVal flag As Boolean)
        '*********************************************************************
        '********************************************************************
        '2009年06月10日 李吉鹏修改 
        Dim length As Integer
        If (Me.cboRef.SelectedIndex = 0) Then
            length = 4
        Else
            length = 3
        End If
        For i As Integer = 0 To length
            Me.DataGridView1.Columns(i).Visible = flag
        Next
    End Sub

    Private Sub dtpFrom_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dtpFrom.ValueChanged

    End Sub
End Class
